package comment

import (
	"strconv"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/Core"
	"git.oschina.net/fuxiaohei/fuxiaohei-go.git/App/admin"
)

type Admin struct {

}

func (this Admin) Setup() {
	Core.SetRoute("GET:/admin/comments", "[I]comment.Admin.ListAction")
	Core.SetRoute("POST:/admin/comments/reply", "[I]comment.Admin.PostAction")
	Core.SetRoute("POST:/admin/comments/status", "[I]comment.Admin.StatusAction")
	Core.SetRoute("DELETE:/admin/comments", "[I]comment.Admin.DeleteAction")
}

func (_ Admin) ListAction(request *Core.HxRequest, response *Core.HxResponse) {
	if !admin.LoginCheck(request) {
		admin.LoginDestroy(response)
		return
	}
	page := 1
	status := "pending"
	if len(request.Param) >= 4 {
		status = request.Param[3]
		if status == "" {
			status = "pending"
		}
	}
	if len(request.Param) >= 6 {
		page, _ = strconv.Atoi(request.Param[5])
		if page < 1 {
			page = 1
		}
	}
	data := make(map[string]interface {})
	data["Group"] = StatusGroup()
	data["Comments"], data["Pager"] = adminList(page, 6, map[string]string{"status":status}, "/admin/comments/" + status + "/")
	data["Status"] = status
	response.Body = admin.RenderAdminPage("comment/list.html", data, nil, "comment")
}

func (_ Admin) PostAction(request *Core.HxRequest, response *Core.HxResponse) {
	if !admin.LoginCheck(request) {
		admin.LoginDestroy(response)
		return
	}
	data := request.Input().All()
	res := map[string]interface {}{"res":false}
	if data["content"] == "" {
		res["msg"] = "内容不能为空"
		response.Json(res)
		return
	}
	res["comment"] = AddReply(request.Cookie("user_id"), data)
	res["res"] = true
	response.Json(res)
}

func (_ Admin) DeleteAction(request *Core.HxRequest, response *Core.HxResponse) {
	if !admin.LoginCheck(request) {
		admin.LoginDestroy(response)
		return
	}
	if len(request.Param) < 4 {
		response.Status = 400
		return
	}
	id := request.Param[3]
	DeleteOne(id)
	res := map[string]interface {}{"res":true}
	response.Json(res)
}

func (_ Admin) StatusAction(request *Core.HxRequest, response *Core.HxResponse) {
	if !admin.LoginCheck(request) {
		admin.LoginDestroy(response)
		return
	}
	data := request.Input().All()
	UpdateStatus(data["id"], data["status"])
	res := map[string]interface {}{"res":true}
	response.Json(res)
}
